package com.smile.f213;
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class KeyEventDemo {
	private JTextArea textArea;
	private JTextField textField;
	private String actions = "";
	public void createUI(){
		JFrame frame = new JFrame("键盘事件处理示例");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		textArea = new JTextArea();
		textField = new JTextField(15);
		textField.addKeyListener(new KeyHandler());
		frame.add(textArea,BorderLayout.SOUTH);
		frame.add(textField,BorderLayout.CENTER);
		frame.setSize(250,120);
		frame.setVisible(true);
	}
	class KeyHandler implements KeyListener{
		@Override
		public void keyPressed(KeyEvent e) {
			actions += "按键" + e.getKeyText(e.getKeyCode()) + "被按下。\n";
			textArea.setText(actions);
		}
		@Override
		public void keyReleased(KeyEvent e) {
			actions += "按键" + e.getKeyText(e.getKeyCode()) + "被释放。\n";
			textArea.setText(actions);
		}
		@Override
		public void keyTyped(KeyEvent e) {
			actions += "按键" + e.getKeyChar() + "被输入。\n";
			textArea.setText(actions);			
		}
	}
	public static void main(String[] args) {
		KeyEventDemo keyDemo = new KeyEventDemo();
		keyDemo.createUI();
	}
}